﻿@namespace Blazorise.Docs.Docs.Examples
@using System.Collections.ObjectModel;
@using Blazorise.Extensions

<Row>
    <Column>
        <Button Clicked="@OnAddNodeClick" Color="Color.Primary">Add node</Button>
        <Button Clicked="@OnRemoveNodeClick" Color="Color.Danger">Remove node</Button>
    </Column>
    <Column>
        <TreeView Nodes="Items"
                  GetChildNodes="@(item => item.Children)"
                  HasChildNodes="@(item => item.Children?.Any() == true)"
                  @bind-SelectedNode="selectedNode"
                  @bind-ExpandedNodes="expandedNodes">
            <NodeContent>
                <Icon Name="IconName.Folder" />
                @context.Text
            </NodeContent>
        </TreeView>
    </Column>
</Row>

@code {
    private Task OnAddNodeClick()
    {
        Items.Add( new Item { Text = $"Item {Items.Count + 1}" } );

        return Task.CompletedTask;
    }

    private async Task OnRemoveNodeClick()
    {
        if ( selectedNode is null )
            return;

        await RemoveItem( selectedNode );
    }

    public Task RemoveItem( Item item )
    {
        SearchTryRemoveItem( Items, item );
        return Task.CompletedTask;
    }

    private void SearchTryRemoveItem( ObservableCollection<Item> rows, Item item )
    {
        if ( rows.IsNullOrEmpty() )
            return;

        var nodeToRemove = rows.FirstOrDefault( x => x.Equals( item ) );

        if ( nodeToRemove is not null )
        {
            rows.Remove( nodeToRemove );
        }
        else
        {
            foreach ( var row in rows )
            {
                SearchTryRemoveItem( row.Children, item );
            }
        }
    }

    public class Item
    {
        public string Text { get; set; }
        public ObservableCollection<Item> Children { get; set; }
    }

    ObservableCollection<Item> Items = new()
    {
        new Item { Text = "Item 1" },
        new Item
        {
            Text = "Item 2",
            Children = new ObservableCollection<Item>()
            {
                new Item { Text = "Item 2.1" },
                new Item
                {
                    Text = "Item 2.2",
                    Children = new ObservableCollection<Item>()
                    {
                        new Item { Text = "Item 2.2.1" },
                        new Item { Text = "Item 2.2.2" },
                        new Item { Text = "Item 2.2.3" },
                        new Item { Text = "Item 2.2.4" }
                    }
                },
                new Item { Text = "Item 2.3" },
                new Item { Text = "Item 2.4" }
            }
        },
        new Item { Text = "Item 3" },
    };

    IList<Item> expandedNodes = new List<Item>();
    Item selectedNode;
}